//
//  HomeFacialHealthView.swift
//  月升
//
//  Created by 拉利法 on 2024/7/12.
//

import UIKit

/// 面容健康
class HomeFacialHealthView: QICategoryView {

    private var leftBtn = UIButton()
    private var rightBtn = UIButton()
    private var showType = 1
    private var page = 1
    /// 肤质
    private var skinModelArr = [QIBeautyMakeupCollectionListModel]()
    /// 美妆收藏
    private var beautyMakeupModelArr = [QIBeautyMakeupCollectionListModel]()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = ColorEEEEEE
        addUI()
        getSkinTypeData()
    }
    
    private func addUI() {
        
        leftBtn = UIButton().then {
            $0.frame = CGRect(x: SCREEN_WIDTH / 2 - 100, y: 10, width: 90, height: 40)
            $0.backgroundColor = MainColor
            $0.titleLabel?.font = FONT(ofSize: 18)
            $0.setTitle("膚質", for: .normal)
            $0.setTitleColor(.white, for: .normal)
            $0.addRoundedCorners(withRadius: 8)
            $0.addBorder(withWidth: 1, borderColor: MainColor)
            $0.addTarget(self, action: #selector(leftBtnClick), for: .touchUpInside)
        }
        self.addSubview(leftBtn)
        
        rightBtn = UIButton().then {
            $0.frame = CGRect(x: SCREEN_WIDTH / 2 + 10, y: 10, width: 90, height: 40)
            $0.titleLabel?.font = FONT(ofSize: 18)
            $0.setTitle("美妝收藏", for: .normal)
            $0.setTitleColor(MainColor, for: .normal)
            $0.addRoundedCorners(withRadius: 8)
            $0.addBorder(withWidth: 1, borderColor: MainColor)
            $0.addTarget(self, action: #selector(rightBtnClick), for: .touchUpInside)
        }
        self.addSubview(rightBtn)
        
        self.addSubview(tableView)
    }
    
    @objc private func leftBtnClick() {
        leftBtn.backgroundColor = MainColor
        leftBtn.setTitleColor(.white, for: .normal)
        rightBtn.backgroundColor = .white
        rightBtn.setTitleColor(MainColor, for: .normal)
        showType = 1
        getSkinTypeData()
    }
    @objc private func rightBtnClick() {
        rightBtn.backgroundColor = MainColor
        rightBtn.setTitleColor(.white, for: .normal)
        leftBtn.backgroundColor = .white
        leftBtn.setTitleColor(MainColor, for: .normal)
        showType = 2
        getBeautyMakeupCollectionData()
    }
    
    private func getSkinTypeData() {
        QINetworkManager.requestJson(urlStr: "/Skin/skin_list", parameters: ["page": page]) { json in
//            print(json)
            self.skinModelArr = json.arrayObject?.kj.modelArray(QIBeautyMakeupCollectionListModel.self) ?? [QIBeautyMakeupCollectionListModel]()
            self.tableView.reloadData()
            self.tableView.mj_header?.endRefreshing()
            self.tableView.mj_footer?.endRefreshing()
        }
        
    }
    
    private func getBeautyMakeupCollectionData() {
        QINetworkManager.requestJson(urlStr: "/Skin/collect_list", parameters: ["page": page]) { json in
            print(json)
            self.beautyMakeupModelArr = json.arrayObject?.kj.modelArray(QIBeautyMakeupCollectionListModel.self) ?? [QIBeautyMakeupCollectionListModel]()
            self.tableView.reloadData()
            self.tableView.mj_header?.endRefreshing()
            self.tableView.mj_footer?.endRefreshing()
        }
        
    }
    
    private lazy var tableView: UITableView = {
        let tableView = UITableView()
        tableView.frame = CGRect(x: 0, y: 60, width: SCREEN_WIDTH, height: self.height - 60)
        tableView.backgroundColor = ColorEEEEEE
        tableView.separatorStyle = .none
        tableView.delegate = self
        tableView.dataSource = self
        tableView.mj_header = MJRefreshNormalHeader(refreshingBlock: {
            self.page = 1
            if self.showType == 1 {
                self.skinModelArr.removeAll()
                self.getSkinTypeData()
            } else {
                self.beautyMakeupModelArr.removeAll()
                self.getBeautyMakeupCollectionData()
            }
        })
        tableView.mj_footer = MJRefreshBackNormalFooter(refreshingBlock: {
            self.page += 1
            if self.showType == 1 {
                self.getSkinTypeData()
            } else {
                self.getBeautyMakeupCollectionData()
            }
        })
        if #available(iOS 15.0, *) {
            tableView.sectionHeaderTopPadding = 0
        } else {}
        return tableView
    }()
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

extension HomeFacialHealthView: UITableViewDataSource, UITableViewDelegate {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        if showType == 1 {
            return skinModelArr.count
        } else {
            return beautyMakeupModelArr.count
        }
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if showType == 1 {
            return skinModelArr[section].skin.count
        } else {
            return beautyMakeupModelArr[section].collect.count
        }
    }
    
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        if showType == 1 {
            return skinModelArr[section].date
        } else {
            return beautyMakeupModelArr[section].date
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        110
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = HomeFacialHealthCell()
        cell.selectionStyle = .none
        if showType == 1 {
            cell.model = skinModelArr[indexPath.section].skin[indexPath.row]
        } else {
            cell.model = beautyMakeupModelArr[indexPath.section].collect[indexPath.row]
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let cell = tableView.cellForRow(at: indexPath) as! HomeFacialHealthCell
        if showType == 1 {
            let model = skinModelArr[indexPath.section].skin[indexPath.row]
            getFuZhiData(idStr: model.id, img: (cell.leftImgView.image ?? UIImage(named: "noo"))!)
        } else {
            let model = beautyMakeupModelArr[indexPath.section].collect[indexPath.row]
            getMeiZhuangData(idStr: model.id, type: model.type, aiImg: (cell.leftImgView.image ?? UIImage(named: "noo"))!)
        }
    }
    
    /// 获取肤质信息
    private func getFuZhiData(idStr: String, img: UIImage) {
        QINetworkManager.requestJson(urlStr: "/Skin/skin_detail", parameters: ["id": idStr]) { json in
//            print(json)
            let raw_file_path = json["raw_file_path"].stringValue
            let event_name = json["event_name"].stringValue
            let resultModel = json["details"].dictionaryObject?.kj.model(QISkinAnalysisResultsModel.self) ?? QISkinAnalysisResultsModel()
            let ctl = SkinAnalysisViewController()
            ctl.img = img
            ctl.raw_file_path = raw_file_path
            ctl.event_name = event_name
            ctl.resultModel = resultModel
            self.navigationController?.pushViewController(ctl, animated: true)
        }
    }
    
    /// 获取美妆信息
    private func getMeiZhuangData(idStr: String, type: String, aiImg: UIImage) {
        QINetworkManager.requestJson(urlStr: "/Skin/collect_detail", parameters: ["id": idStr]) { json in
//            print(json)
            let event_name = json["event_name"].stringValue
            let raw_file_path = json["raw_file_path"].stringValue
            let facial_data_code_string = json["facial_data_code_string"].stringValue
            let name = json["name"].stringValue
            let video_id = json["video_id"].stringValue
            let video = json["video"].stringValue
            let video_code = json["video_code"].stringValue
            let Local_Save_Path = json["local_save_path"].stringValue
            let originalImgUrl = json["original_drawing"].stringValue
            let lipstick = json["lipstick"].dictionaryObject
            let eye_shadow = json["eye_shadow"].dictionaryObject
            let powder_blusher = json["powder_blusher"].dictionaryObject
            var wuGuanModel = QIFiveSensesResultModel()
            wuGuanModel.facial_data_code_string = facial_data_code_string
            var model = QIBeautyRecommenListModel()
            model.title = name
            model.video_link = video
            model.video_code = video_code
            model.vModel.video_code = video_code
            model.vModel.id = video_id
            model.isCollect = true
            model.id = json["id"].stringValue
            
            if type == "1" {
                let ctl = FilterCriteriaVideoInfoViewController()
                ctl.previewImg = aiImg
                ctl.originalImgUrl = originalImgUrl
                ctl.model = model
                ctl.event_name = event_name
                ctl.wuGuanModel = wuGuanModel
                ctl.raw_file_path = raw_file_path
                ctl.followID = idStr
                self.navigationController?.pushViewController(ctl, animated: true)
            } else {
                let ctl = AIMakeupViewController()
                ctl.previewImg = aiImg
                ctl.event_name = event_name
                ctl.Local_Save_Path = Local_Save_Path
                ctl.originalImgUrl = originalImgUrl
                ctl.videoModel = model
                ctl.eye_shadow = eye_shadow ?? [String: Any]()
                ctl.powder_blusher = powder_blusher ?? [String: Any]()
                ctl.lipstick = lipstick ?? [String: Any]()
                self.navigationController?.pushViewController(ctl, animated: true)
            }
        }
        
    }
    
}



class HomeFacialHealthCell: UITableViewCell {
    
    var leftImgView = UIImageView()
    private var nameL = UILabel()
    private var fenciL = UILabel()
    private var maokongL = UILabel()
    private var zhouwenL = UILabel()
    private var titleL1 = UILabel()
    private var titleL2 = UILabel()
    private var titleL3 = UILabel()
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        self.backgroundColor = ColorEEEEEE
        addUI()
    }
    func addUI() {
        
        let bgView = UIView()
        bgView.frame = CGRect(x: 17, y: 5, width: SCREEN_WIDTH - 34, height: 100)
        bgView.backgroundColor = .white
        bgView.addRoundedCorners(withRadius: 10)
        self.addSubview(bgView)
        
        leftImgView = UIImageView().then {
            $0.frame = CGRect(x: 10, y: 10, width: 80, height: 80)
            $0.image = UIImage(named: "008")
            $0.contentMode = .scaleAspectFill
            $0.clipsToBounds = true
            $0.addRoundedCorners(withRadius: 8)
        }
        bgView.addSubview(leftImgView)
        
        nameL = UILabel().then({
            $0.frame = CGRect(x: leftImgView.right + 10, y: 10, width: bgView.width - 110, height: 50)
            $0.text = "日系小清新，搭配《猫眼-玫瑰红》眼影"
            $0.textColor = Color333333
            $0.numberOfLines = 3
            $0.font = FONTBOLD(ofSize: 12)
        })
        bgView.addSubview(nameL)
        
        let detailL = UILabel().then({
            $0.frame = CGRect(x: bgView.width - 45, y: bgView.height - 32, width: 30, height: 17)
            $0.text = "详情"
            $0.textColor = MainColor
            $0.textAlignment = .right
            $0.font = FONT(ofSize: 12)
        })
        bgView.addSubview(detailL)
        
        
        
        // 肤质
        titleL1 = UILabel().then({
            $0.frame = CGRect(x: leftImgView.right + 10, y: 15, width: 33, height: 20)
            $0.text = "粉刺:"
            $0.textColor = Color999999
            $0.font = FONT(ofSize: 14)
        })
        bgView.addSubview(titleL1)
        
        fenciL = UILabel().then({
            $0.frame = CGRect(x: titleL1.right + 10, y: 15, width: 170, height: 20)
            $0.text = "正常"
            $0.textColor = Color333333
            $0.font = FONTBOLD(ofSize: 12)
        })
        bgView.addSubview(fenciL)
        
        titleL2 = UILabel().then({
            $0.frame = CGRect(x: leftImgView.right + 10, y: 20, width: 33, height: 20)
            $0.centerY = leftImgView.centerY
            $0.text = "毛孔:"
            $0.textColor = Color999999
            $0.font = FONT(ofSize: 14)
        })
        bgView.addSubview(titleL2)
        
        maokongL = UILabel().then({
            $0.frame = CGRect(x: titleL1.right + 10, y: 20, width: 170, height: 20)
            $0.centerY = leftImgView.centerY
            $0.text = "正常"
            $0.textColor = Color333333
            $0.font = FONTBOLD(ofSize: 12)
        })
        bgView.addSubview(maokongL)
        
        titleL3 = UILabel().then({
            $0.frame = CGRect(x: leftImgView.right + 10, y: leftImgView.bottom - 25, width: 33, height: 20)
            $0.text = "皱纹:"
            $0.textColor = Color999999
            $0.font = FONT(ofSize: 14)
        })
        bgView.addSubview(titleL3)
        
        zhouwenL = UILabel().then({
            $0.frame = CGRect(x: titleL1.right + 10, y: 20, width: 170, height: 20)
            $0.centerY = titleL3.centerY
            $0.text = "正常"
            $0.textColor = Color333333
            $0.font = FONTBOLD(ofSize: 12)
        })
        bgView.addSubview(zhouwenL)
        
    }
    
    var model = QIBeautyMakeupCollectionModel() {
        didSet {
            // 肤质
            if model.wrinkles_report.count > 0 {
                nameL.isHidden = true
                fenciL.text = model.acne_report
                maokongL.text = model.pores_report
                zhouwenL.text = model.wrinkles_report
                titleL1.isHidden = false
                titleL2.isHidden = false
                titleL3.isHidden = false
                fenciL.isHidden = false
                maokongL.isHidden = false
                zhouwenL.isHidden = false
            } else {    //美妆收藏
                nameL.text = model.name
                titleL1.isHidden = true
                titleL2.isHidden = true
                titleL3.isHidden = true
                fenciL.isHidden = true
                maokongL.isHidden = true
                zhouwenL.isHidden = true
            }
            leftImgView.kf.setImage(with: URL(string: model.image))
        }
    }
    
    
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
}

